package com.ml.mall.listener;

import com.alibaba.fastjson.JSON;
import com.ml.mall.config.MailProperties;
import com.ml.mall.consts.MailConsts;
import com.ml.mall.exception.BizException;
import com.ml.mall.model.MailMessage;
import com.ml.mall.utils.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;

/**
 * @author :zxm
 * @date :2021/3/6 14:00
 * @description :监听发送邮件的队列
 **/
@Component
@Slf4j
public class MailListener {

    @Autowired
    private MailProperties mailProperties;

//    @Scheduled(cron = "0/10 * * * * ?")
    public void timeSend(){
        // 从redis中获取邮件，每10s发送一次，一次发送10条
        List<String> messageList = RedisClient.lrange(MailConsts.REDIS_MAIL_MESSAGE, 0, 9);
        if(messageList!=null && messageList.size()!=0){
            for (String msg : messageList) {
                RedisClient.lrem(MailConsts.REDIS_MAIL_MESSAGE,1L,msg);
                MailMessage mailMessage = JSON.parseObject(msg, MailMessage.class);
                Integer type = mailMessage.getType()==null?MailConsts.INFO_TYPE:mailMessage.getType();
                sendMail(mailMessage,type);
            }
        }
    }

    private void sendMail(MailMessage message,Integer type) {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put(MailConsts.MAIL_SMTP_AUTH, mailProperties.getIsAuth());
        props.put(MailConsts.MAIL_SMTP_HOST, mailProperties.getSmtpHost());
        // 发件人的账号
        if(MailConsts.INFO_TYPE.equals(type)){
            props.put(MailConsts.MAIL_USER, mailProperties.getInfoMailUser());
        }else {
            props.put(MailConsts.MAIL_USER, mailProperties.getOrderMailUser());
        }
        // 访问SMTP服务时需要提供的密码
        props.put(MailConsts.MAIL_PASSWORD, mailProperties.getMailPwd());
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty(MailConsts.MAIL_USER);
                String password = props.getProperty(MailConsts.MAIL_PASSWORD);
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage mimeMessage = new MimeMessage(mailSession);
        try {
            // 设置发件人
            InternetAddress form = new InternetAddress(props.getProperty(MailConsts.MAIL_USER));
            mimeMessage.setFrom(form);
            // 设置收件人
            InternetAddress to = new InternetAddress(message.getEmail());
            mimeMessage.setRecipient(Message.RecipientType.TO, to);
            // 构建消息
            mimeMessage.setSubject(message.getSubject());
            mimeMessage.setContent(message.getText(),"text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(mimeMessage);
        } catch (Exception e) {
            log.error("mail======exception======{}",e.getMessage());
        }
    }

}
